import {Buffer} from "buffer";
import {DataUtils} from "../DataUtils";


export class HdlcAddress {

    byteLength: number = 0;
    logicalDeviceAddress: number = 0;
    physicalDeviceAddress: string = "";

    constructor(logicalDeviceAddress: number, physicalDeviceAddress: string) {
        this.byteLength = physicalDeviceAddress.length % 2 == 0 ? physicalDeviceAddress.length / 2 : (physicalDeviceAddress.length + 1) / 2;
        ++this.byteLength;
        this.logicalDeviceAddress = logicalDeviceAddress;
        this.physicalDeviceAddress = physicalDeviceAddress;
    }

    getLogicalDeviceAddress(): number {
        return this.logicalDeviceAddress >> 4 & 0x30;
    }

    getAddressType(): number {
        return this.logicalDeviceAddress >> 6 & 0x3;
    }

    setAddressType(addressType: number) {
        this.logicalDeviceAddress = (this.logicalDeviceAddress & 0x3F | (addressType & 0x3) << 6);
    }

    getPhysicalDeviceAddress(): string {
        return this.physicalDeviceAddress;
    }

    getByteLength(): number {
        return this.byteLength;
    }

    static decode(data : Buffer) : HdlcAddress{
        let logicalDeviceAddr;
        let physicalDevAddr;
        logicalDeviceAddr = data[0] & 0x30;
        let addlen = (data[0] & 0xF) + 1;
        physicalDevAddr = DataUtils.toShortHexString(data, 1, addlen, true);
        return new HdlcAddress(logicalDeviceAddr, physicalDevAddr);
    }

    encode(): Buffer {
        let firstaddr;
        let result = Buffer.alloc(this.byteLength);
        firstaddr = this.logicalDeviceAddress & 0xF0;
        firstaddr = firstaddr | this.byteLength - 2 & 0xF;
        result[0] = firstaddr;
        if (this.physicalDeviceAddress.length % 2 == 1) {
            this.physicalDeviceAddress += "F";
        }
        console.log(this.physicalDeviceAddress);
        let srvaddr = DataUtils.fromShortHexString(this.physicalDeviceAddress, true);
        srvaddr.copy(result, 1, 0, srvaddr.length)
        return result;
    }

    toString() : string{
        let s = "";
        let ldLength = (this.byteLength + 1) / 2 * 2;
        let phLength = this.byteLength / 2 * 2;
        s += "%0" + ldLength + "X" + this.logicalDeviceAddress;
        if (phLength > 0) {
            s += "-%0" + phLength + "X" + this.physicalDeviceAddress;
        }
        return s;
    }

}
